package at.ac.tuwien.vpsbcm.spielzeugfabrik.space;

import java.util.Random;

import org.mozartspaces.capi3.FifoCoordinator;
import org.mozartspaces.capi3.LindaCoordinator;
import org.mozartspaces.core.Capi;
import org.mozartspaces.core.ContainerReference;
import org.mozartspaces.core.Entry;
import org.mozartspaces.core.MzsCoreException;

import at.ac.tuwien.vpsbcm.spielzeugfabrik.BauteilEnum;

public class Produzent implements Runnable {

	public static final int DELAY_MIN_MS = 1000;
	public static final int DELAY_MAX_MS = 3000;
	
	private int id;
	private BauteilEnum bauteil;
	private int anzahl;
	private Capi capi;
	private ContainerReference container;
	
	public Produzent (Capi capi, ContainerReference container, int id, BauteilEnum bauteil, int anzahl) {
		// get id and store it
		this.id = id;
		this.bauteil = bauteil;
		this.anzahl = anzahl;
		this.capi = capi;
		this.container = container;
	}
	
	public void run() {
		int i;
		Entry entry;
		String FifoName = "";
		Random rand = new Random ();
		if (this.bauteil == BauteilEnum.RAD) {
			FifoName = "RAD";			
		} else {
			FifoName = "unlackierte";
		}
		System.out.format("Started Thread for Producer %d, Part %s\n", this.id, this.bauteil);
		for (i=0; i<this.anzahl; i++) {
			try {
				Thread.sleep(rand.nextInt (DELAY_MAX_MS - DELAY_MIN_MS + 1) + DELAY_MIN_MS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			entry = new Entry (new Bauteil(this.id, i, this.bauteil, false, "", null), LindaCoordinator.newCoordinationData(), FifoCoordinator.newCoordinationData(FifoName));
			try {
				capi.write(container, entry);
			} catch (MzsCoreException e) {
				e.printStackTrace();
			}
			System.out.format("Producer %d, Part %s, Number %d\n", this.id, this.bauteil, i);
			
		
		}
		System.out.format("Stopping Thread for Producer %d, Part %s\n", this.id, this.bauteil);

	}

}
